<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="pay_mode" label="收款类型" required>
        <uni-data-checkbox v-model="formData.pay_mode" :localdata="formOptions.pay_mode_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <div v-if="formData.pay_mode==1">
        <uni-forms-item name="bank_terminal_name" label="开户银行" required>
            <uni-data-select
              v-model="formData.bank_terminal_name"
              :localdata="selectBankList"
            ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item name="bank_number" label="银行账号" required>
          <uni-easyinput placeholder="提款银行账号" v-model="formData.bank_number"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="bank_account_name" label="持有人名称" required>
          <uni-easyinput placeholder="银行卡持有人名称" v-model="formData.bank_account_name"></uni-easyinput>
        </uni-forms-item>
      </div>
      <uni-forms-item name="enable_status" label="启用或关闭" required>
        <switch style="transform: scale(0.8);" @change="binddata('enable_status', $event.detail.value)" :checked="formData.enable_status"></switch>
      </uni-forms-item>
      <view class="uni-button-group">
        <lay-button type="normal" @click="submit">确认提交</lay-button>
        <lay-button @click="closeAll">取消关闭</lay-button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/food-withdraw-mode.js';
  import {BANK_NAME_TOGGLE}  from '~@/common/bank-class.js'
  import {store} from '@/uni_modules/uni-id-pages/common/store.js'
  import lodash from 'lodash'

  let throttled =null
  const dynamicValidatorFields={
    // 银行卡
    1:['bank_number',`bank_account_name`,`bank_terminal_name`], 
    // 微信
    0:[]
  }
  
  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food-withdraw-mode';


  function getValidator(fields,extra) {
    let result = {}
    const excludeFieds = Object.values(dynamicValidatorFields).flat(2)
    fields=fields.filter(it=>{
      return !excludeFieds.includes(it)
    })
    if(extra){
      fields=fields.concat(extra)
    }
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  function getBankAccountType(cardNo){
    return new Promise(resolve=>{
      fetch(`https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?cardNo=${cardNo}&cardBinCheck=true`)
      .then((response) => response.json())
      .then((data) => {
        if(data.validated&&data.stat==='ok'){
            this.formData.bank_terminal_name=data.bank
        }
        resolve(data)
      });
    })
  }
  
  export default {
    data() {
      let formData = {
        "user_id": "",
        "pay_mode": 0,
        "bank_number": "",
        "bank_account_name": "",
        "bank_terminal_name": "",
        "enable_status": true
      }
      return {
        selectBankList:Object.entries(BANK_NAME_TOGGLE).map(it=>{ return { value:it[0],text:it[1] } }),

        formData,
        formOptions: {
          "pay_mode_localdata": [
            {
              "value": 0,
              "text": "微信"
            },
            {
              "value": 1,
              "text": "银行卡"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    watch:{
      'formData.bank_number'(value){
        throttled&&throttled()
      },
      'formData.pay_mode'(value){
        this.rules=getValidator(Object.keys(this.formData),dynamicValidatorFields[value])
        this.$refs.form.setRules(this.rules)
      }
    },
    mounted() {
        throttled=lodash.throttle(()=>{
          getBankAccountType.call(this,this.formData.bank_number)
        },3*1000)

      this.$refs.form.setRules(this.rules)
    },
    methods: {
      closeAll(){
        this.$emit(`manualClose`,`addComponent`)
      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then(async (res) => {
          if(res.pay_mode==1){  // 银行卡的情况下
            const numberAssert = await getBankAccountType.call(this,res.bank_number)
            if(!numberAssert.validated){
                return layer.msg(`银行账户不可用，请重新输入`, { icon : 2, time: 1500})
            }
          }else{ // 银行卡的情况下
            return layer.msg(`微信收款方式不可用，请切换到其他`, { icon : 2, time: 1500})
          }

          res.user_id = store.userInfo._id
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.$emit(`refreshData`)
          this.closeAll();
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
